
from jinja2 import FileSystemLoader, Environment


class TErrorEasyJinja2(Exception):
    def __init__(self, message):
        self.message = message
    def __str__(self):
        return self.message



class TEasyJinja2:
    def __init__(self, tpl_folder:str):
        self.jinja2_loader = FileSystemLoader(searchpath=tpl_folder)
        self.jinja2_environment = Environment(loader=self.jinja2_loader)
        print(f"Load templates from '{tpl_folder}' is successfully")
        return

    def Render(self, user_dict:dict, tpl_file:str, out_file = '', encode = 'utf-8'):
        '''
        选定模板生成目标字符串
        :param user_dict:   用户参数字典
        :param tpl_file:    模板文件
        :param out_file:    输出目标文件
        :param encode:      输出文件编码
        :return:            输出字符串
        '''
        self.jinja2_template = self.jinja2_environment.get_template(tpl_file)
        output = self.jinja2_template.render(user_dict)
        print("\n============================ results display ---- begin ============================")
        print(output)
        print("============================ results display ---- end   ============================")

        if out_file != '' and out_file != '.':
            with open(out_file, 'w', encoding=encode) as f:
                try:
                    f.write(output)
                finally:
                    f.close()
            print(f"File '{out_file}' is successfully generated using template '{tpl_file}'\n")

        return output



if __name__ == "__main__":
    demo = TEasyJinja2("templates")
    user = {"var_name":"jpz", "var_date":"Today"}
    demo.Render(user, "sub1/sub_hq_c_head.tpl", "test1.txt")





